using System;
using System.Collections.Generic;
using System.Text;

namespace DataSchema.Model
{
    static public class ModelMgr
    {
        #region PROPERTY
        static private Model.ModelSchema _models;
        static private string _modelPath = "models.xml";
        #endregion

        #region STATIC CONTRUCTOR
        static ModelMgr()
        {
            _models = new ModelSchema();
            if (new System.IO.FileInfo(_modelPath).Exists == false)
            {
                _models.WriteXml(_modelPath);
            }
            else
                _models.ReadXml(_modelPath);
        }
        #endregion

        #region TOOLS
        static public Model.ModelSchema.ModelRow[] Find(string name)
        {
            string sql = string.Format("Upper(Name) like '%0%", name.Replace("'", "''"));
            return _models.Model.Select(sql) as Model.ModelSchema.ModelRow[];
        }

        static public Model.ModelSchema.ModelRow Add(string name)
        {
            string sql = string.Format("Upper(Name) like '%0%", name.Replace("'", "''"));
            Model.ModelSchema.ModelRow[] rs = _models.Model.Select(sql) as Model.ModelSchema.ModelRow[];
            if (rs != null && rs.Length >= 1)
                return rs[0];
            Model.ModelSchema.ModelRow nr = _models.Model.NewModelRow();
            nr.Name = name;
            _models.Model.Rows.Add(nr);
            return nr;
        }

        static public void Save()
        {
            _models.WriteXml(_modelPath);
        }

        #endregion
    }
}
